import { FC, useEffect, useState, useRef } from "react";
import { Modal } from "@arco-design/web-react";
import Button from "@mui/material/Button";
import { css } from "@emotion/css";
import Card from "@mui/material/Card";
import { IconCloseCircle } from "@arco-design/web-react/icon";
import Grid from "@mui/material/Grid";
import Hls from "hls.js";

export interface ViewVideoRecordModalProps {
  visible?: boolean;

  onClose?: () => void;
}

export const VideoModal: FC<ViewVideoRecordModalProps> = ({
  visible,
  onClose,
}) => {
  const [videoElement, setVideoElement] = useState<HTMLVideoElement>();
  const src = `https://stream.seysoai.cn/stream1chl.m3u8`;
  const [error, setError] = useState("");
  const hlsRef = useRef<any>();

  useEffect(() => {
    if (!visible || !videoElement) return;

    // 清除之前的错误
    setError("");

    if (Hls.isSupported()) {
      const hls = new Hls({
        maxBufferLength: 30,
        maxMaxBufferLength: 600,
        maxBufferSize: 60 * 1000 * 1000,
        maxBufferHole: 0.5,
        lowLatencyMode: false,
        enableWorker: true,
      });

      hls.on(Hls.Events.ERROR, (data: any) => {
        if (data.fatal) {
          switch (data.type) {
            case Hls.ErrorTypes.NETWORK_ERROR:
              setError("网络错误，请检查您的连接");
              break;
            case Hls.ErrorTypes.MEDIA_ERROR:
              setError("媒体错误，请重试");
              break;
            default:
              setError("播放失败");
              break;
          }
          hls.destroy();
        }
      });

      hls.loadSource(src);
      hls.attachMedia(videoElement);
      hls.on(Hls.Events.MANIFEST_PARSED, () => {
        videoElement
          .play()
          .catch((e: any) => console.log("Autoplay prevented:", e));
      });
      hlsRef.current = hls;
    } else if (videoElement.canPlayType("application/vnd.apple.mpegurl")) {
      // 原生 HLS 支持（Safari）
      videoElement.src = src;
      videoElement.addEventListener("loadedmetadata", () => {
        videoElement
          .play()
          .catch((e: any) => console.log("Autoplay prevented:", e));
      });
    } else {
      setError("您的浏览器不支持 HLS 播放");
    }
    // }

    return () => {
      if (hlsRef.current) {
        hlsRef.current.destroy();
      }
    };
  }, [src, visible, videoElement]);
  return (
    <Modal
      className={css`
        max-width: 1000px;
        background: rgba(0, 0, 0, 0);
      `}
      visible={visible}
      onCancel={onClose}
      closable={false}
      unmountOnExit
      mountOnEnter
      footer={null}
    >
      <Card
        sx={{ width: 600 }}
        style={{ textAlign: "center", paddingBottom: "10px" }}
      >
        <div style={{ position: "relative" }}>
          <video
            ref={(el: any) => setVideoElement(el)}
            controls
            style={{ width: 600,height: 400 }}
          />
          {error && (
            <div
              style={{
                position: "absolute",
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                backgroundColor: "rgba(0,0,0,0.7)",
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                color: "white",
                fontSize: "18px",
              }}
            >
              {error}
            </div>
          )}
        </div>
        <Grid item>
          <Button
            variant="contained"
            color="secondary"
            startIcon={<IconCloseCircle />}
            onClick={() => {
              onClose?.();
            }}
          >
            关闭
          </Button>
        </Grid>
      </Card>
    </Modal>
  );
};
